<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Home;

use App\Http\Controllers\Controller;
use App\Modules\User\Services\UserService;
use App\Modules\Home\Services\ArchivesService;
use App\Modules\Task\Services\TaskService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 我的 - 个人中心
 * Class HomeController
 * @package App\Http\Controllers\Api\Home
 */
class HomeController extends Controller
{
    /**
     * 个人中心首页
     */
    public function homeIndex(){
        $health = 0;        //已填个数
        $userData = $this->getLoginUser();
//        $user_id = 1;
        //查询用户信息（该步骤正式环境不需要查找，直接$this->getLoginUser()获取）
        empty($userData->name) ? : $health += 1;
        empty($userData->gender) ? : $health += 1;
        empty($userData->birth_at) ? : $health += 1;
        empty($userData->papers_type) ? : $health += 1;
        empty($userData->papers) ? : $health += 1;
        empty($userData->height) ? : $health += 1;
        empty($userData->weight) ? : $health += 1;
        $archivesData = DB::table('archives')->where('user_id',$userData->id)->first();
        if ( !empty($archivesData) ) {
            empty($archivesData->dm_age) ? : $health += 1;
            empty($archivesData->complication) ? : $health += 1;
            empty($archivesData->treatment) ? : $health += 1;
            empty($archivesData->dm_type) && $archivesData->dm_type !== 0 ? : $health += 1;
            empty($archivesData->is_smoke) && $archivesData->is_smoke !== 0 ? : $health += 1;
            empty($archivesData->is_drink) && $archivesData->is_drink !== 0 ? : $health += 1;
        }
        $health = round($health / 13 * 100);
        //获取系统消息数量
        $noticeCount = DB::table('notice')->where(['recipient_id'=>$userData->id,'is_reading'=>0])->orWhere('created_at','>=',$userData->system_notice_at)->count();
        //返回数据
        $result = [
            'id'            => $userData->id,
            'phone'         => $userData->phone,
            'vip'           => $userData->vip,
            'balance'       => $userData->balance,
            'vip_end_at'    => $userData->vip_end_at,
            'health_per'    => $health,
            'notice_count'  => $noticeCount

        ];
        return response()->success($result);
    }

    /**
     * 个人健康档案
     */
    public function healthArchives(Request $request){
        $user_id = $this->getLoginUser()->id;
        //获取个人健康档案信息
        $archivesGet = ArchivesService::getArchives($user_id);
//        if ( !empty($archivesGet) ) {
//            $archivesGet->complications = [];
//        }
        if ( !empty($archivesGet->dm_age) ) {
            $archivesGet->dm_age = getMonthNum($archivesGet->dm_age,date('Y-m-d H:i:s',time()));
        }
        //获取并发症（后续修改，直接保存字符串。不做查询）
//        if ( !empty($archivesGet->complication) ) {
//            $idsArr = explode(',',$archivesGet->complication);
//            $complication = ArchivesService::getComplication($idsArr);
//            $archivesGet->complications = $complication;
//        }
        return response()->success($archivesGet);
    }

    /**
     * 修改个人档案（弃用）
     */
    public function updateArchives(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 1;
        //基本信息
        $dataUpdateArr = ['id'=>$user_id];
        !isset($_POST['name']) ? : $dataUpdateArr['name'] = $request->input('name');
        !isset($_POST['birth_at']) ? : $dataUpdateArr['birth_at'] = $request->input('birth_at');
        !isset($_POST['papers_type']) ? : $dataUpdateArr['papers_type'] = $request->input('papers_type');
        !isset($_POST['papers']) ? : $dataUpdateArr['papers'] = $request->input('papers');
        !isset($_POST['height']) ? : $dataUpdateArr['height'] = $request->input('height');
        !isset($_POST['weight']) ? : $dataUpdateArr['weight'] = $request->input('weight');
        //病史信息
        $dataUpdateArchives = ['user_id'=>$user_id];
        !isset($_POST['dm_type']) ? : $dataUpdateArchives['dm_type'] = $request->input('dm_type');
        !isset($_POST['complication']) ? : $dataUpdateArchives['complication'] = $request->input('complication','');
        !isset($_POST['treatment']) ? : $dataUpdateArchives['treatment'] = $request->input('treatment');
        !isset($_POST['is_smoke']) ? : $dataUpdateArchives['is_smoke'] = $request->input('is_smoke');
        !isset($_POST['is_drink']) ? : $dataUpdateArchives['is_drink'] = $request->input('is_drink');
        //糖龄转换
        if ( isset($_POST['dm_age']) ) {
            $dm_age = $request->input('dm_age',0);
            $dataUpdateArchives['dm_age'] = date('Y-m-d',strtotime("-{$dm_age} month"));
        }
        //个人档案信息
        $archivesGet = ArchivesService::getArchives($user_id);
        //判断是否将当前添加地址设置为默认地址，如果设置为默认地址，修改以前数据的默认地址为0
        DB::beginTransaction();
        try{
            //修改用户信息
            $updateUser = UserService::updateUser($dataUpdateArr);
            if ( empty($updateUser) && $updateUser !== 0 ) {
                throw new \Exception('UPDATE_FAILURE');
            }
            //判断是否有添加个人档案信息，有就修改，没有就添加
            if ( empty($archivesGet) ) {
                //添加健康档案
                $createArchives = ArchivesService::addArchives($dataUpdateArchives);
                if(empty($createArchives)){
                    throw new \Exception('UPDATE_FAILURE');
                }
            }else{
                //修改健康档案
                $updateArchives = ArchivesService::updateArchives($dataUpdateArchives);
                if(empty($updateArchives) && $updateArchives !== 0){
                    throw new \Exception('UPDATE_FAILURE');
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error($e->getMessage());
        }
        return response()->success();
    }

    /**
     * 健康档案单个字段修改
     */
    public function updateField(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 1;
        //查询用户信息（该步骤正式环境不需要查找，直接$this->getLoginUser()获取）
        $userData = DB::table('users')->where('id',$user_id)->first();

        $field = $request->input('field','');
        $value = $request->input('value','');
        $type = $request->input('type',0);      //1个人信息 2病史信息
        if ( empty($field) || empty($type) ) return response()->error("PARAM_EMPTY");
        $fieldArr = ['name','gender','avatar','nickname','birth_at','papers_type','papers','height','weight','dm_type','dm_age','complication','treatment','is_smoke','is_drink'];
        if ( !in_array($field,$fieldArr) ) return response()->error("PARAM_ERROR");
        switch ($type) {
            case 1:
                $result = DB::table('users')->where('id',$user_id)->update([$field=>$value]);
                break;
            case 2:
                //糖龄转换
                if ( $field == 'dm_age' ) {
                    $value = date('Y-m-d',strtotime("-{$value} month"));
                }
                //判断是否有添加过个人健康档案
                $archives = DB::table('archives')->where('user_id',$user_id)->first();
                if ( empty($archives) ) {
                    $createArchivesArr = [
                        'user_id'   => $user_id,
                        $field      => $value
                    ];
                    $result = ArchivesService::addArchives($createArchivesArr);
                }else{
                    $result = DB::table('archives')->where('user_id',$user_id)->update([$field=>$value]);
                }
                break;
            default:
                return response()->error("PARAM_ERROR");
        }
        if ( empty($result) && $result !== 0 ) return response()->error("UPDATE_FAILURE");
        //判断个人档案任务是否完成
        $taskObj = new TaskService();
        $taskObj->archivesTask($user_id,$userData);
        return response()->success();
    }

    /**
     * 每日签到
     * 规则：
     *   连续签到领取健康币规则（暂定方案）：
     *   第一天--5健康币
     *   第二天--10健康币
     *   第三天--15健康币
     *   第四天--20健康币
     *   第五天--30健康币
     *   第六天--40健康币
     *   第七天--50健康币
     *   七天以上--50健康币（期间中断，重新按规则来）
     */
    public function dailySign(Request $request){
//        $sign_at = $request->input('sign_at','');
//        if ( empty($sign_at) || empty(strtotime($sign_at)) ) return response()->error("PARAM_EMPTY");
//        $sign_at = date('Y-m-d',strtotime($sign_at));
        $sign_at = date('Y-m-d',time());
        $signCoinArr = [5,10,15,20,30,40,50];   //奖励金币
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        //判断当前时间参数是否已签到
        $sign = DB::table('daily_sign')->where('user_id',$user_id)->where('sign_at',$sign_at)->count();
        if ( !empty($sign) ) return response()->error("PARAM_ERROR");
        //获取到当前用户最新的签到数据
        $signGet = DB::table('daily_sign')->where('user_id',$user_id)->orderBy('sign_at','DESC')->first();
        //判断是否连续签到
        if ( empty($signGet) ) {
            $coin = $signCoinArr[0];
            $continuous = 1;
        }else{
            $signAt = date('Y-m-d',strtotime('+1 month',strtotime($signGet->sign_at)));
            $nowAt = date('Y-m-d',time());
            //判断最新签到时间加上一天是否跟现在时间一致。一致表示连续签到，获取到相应的金币
            $coin = $signAt == $nowAt ? $signCoinArr[$signGet->continuous] : $signCoinArr[0];
            $continuous = $signGet->continuous + 1;
        }
        $date = date('Y-m-d H:i:s',time());
        //添加数组
        $signInsertArr = [
            'user_id'   => $user_id,
            'sign_at'   => $sign_at,
            'coin'      => $coin,
            'created_at'=> $date,
            'updated_at'=> $date,
            'continuous'=> $continuous
        ];
        //添加签到数据
        DB::beginTransaction();
        try{
            $signInsert = DB::table('daily_sign')->insertGetId($signInsertArr);
            if ( empty($signInsert) ) throw new \Exception('ADD_FAILURE');
            //添加金币账单表
            $coinInsertArr = [
                'user_id'       => $user_id,
                'associated_id' => $signInsert,
                'type'          => 4,
                'created_at'    => $date,
                'updated_at'    => $date,
                'coin'          => $coin,
            ];
            $coinInsert = DB::table('coin')->insert($coinInsertArr);
            if ( empty($coinInsert) ) throw new \Exception('ADD_FAILURE');
            //修改用户金币
            $updateUser = UserService::updateCoin($user_id,$coin);
            if ( empty($updateUser) ) throw new \Exception('UPDATE_FAILURE');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error('SIGN_ERROR');
        }
        return response()->success();
    }
}
























